package com.chat.login.service.impl;


import com.chat.common.common.constant.MessageConstant;
import com.chat.common.common.constant.RedisKeyConstant;
import com.chat.common.common.exception.RoutineException;
import com.chat.common.vo.R;
import com.chat.login.domain.dto.CaptchaDTO;
import com.chat.login.domain.vo.CaptchaVO;
import com.chat.login.domain.vo.VoucherVO;
import com.chat.login.service.CaptchaService;
import com.chat.login.utils.EmailUtils;
import com.chat.login.utils.RedisUtil;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private EmailUtils emailUtils;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public CaptchaVO sendTextMailMessage(String toEmail) {
        String capText = captchaProducer.createText();
        String codeId = UUID.randomUUID().toString();
        redisUtil.setEx(RedisKeyConstant.CAPTCHA_MAIL + codeId, capText, 5, TimeUnit.MINUTES);
        emailUtils.sendEmail(toEmail,"E-chat验证","E-chat提醒您，验证码是：" + capText + "请您5分钟内使用。");
        return new CaptchaVO(codeId);
    }

    @Override
    public R<VoucherVO> validateMailCaptcha(CaptchaDTO captchaDTO) {
        String storedCaptcha = (String) redisUtil.get(RedisKeyConstant.CAPTCHA_MAIL + captchaDTO.getCodeId());
        if(storedCaptcha == null){
            throw new RoutineException(MessageConstant.CAPTCHA_NOT);
        }else if(!storedCaptcha.equals(captchaDTO.getCode())){
            throw new RoutineException(MessageConstant.CAPTCHA_ERROR);
        }
        String voucherId = UUID.randomUUID().toString();
        //账号为key，value为凭证
        redisUtil.setEx(RedisKeyConstant.VOUCHER + captchaDTO.getAccount(), voucherId, 5, TimeUnit.MINUTES);
        //清除验证过的验证码
        redisUtil.delete(RedisKeyConstant.CAPTCHA_MAIL + captchaDTO.getCodeId());
        return R.succeed(new VoucherVO(voucherId));
    }
}
